/**  
 * All rights Reserved, Designed By www.flksh.com
 * @date:   2017-10-28 13:39:23   
 * @Copyright: 2013-2017 www.flksh.com Inc. All rights reserved. 
 * 注意：本内容仅限于上海福乐康社区养老服务有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
package com.zx.cloud.controller;

import java.io.UnsupportedEncodingException;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zx.cloud.ApiVersion;
import com.zx.cloud.RequestLogging;
import com.zx.cloud.common.auth0.jwt.Token;
import com.zx.cloud.common.auth0.jwt.TokenGenerator;
import com.zx.cloud.common.auth0.jwt.exceptions.JWTCreationException;
import com.zx.cloud.common.filter.CurrentUserId;
import com.zx.cloud.common.filter.IgnoreAuth;
import com.zx.cloud.common.filter.MagicConstants;
import com.zx.cloud.domain.Client;
import com.zx.cloud.domain.ClientAuth;
import com.zx.cloud.domain.ClientRisk;
import com.zx.cloud.domain.Dict;
import com.zx.cloud.domain.IdCardImg;
import com.zx.cloud.domain.Proposal;
import com.zx.cloud.domain.SmsMsg;
import com.zx.cloud.domain.VerifyMsg;
import com.zx.cloud.model.response.ObjectDataResponse;
import com.zx.cloud.model.response.Response;
import com.zx.cloud.service.ClientRiskService;
import com.zx.cloud.service.ClientService;
import com.zx.cloud.service.DictService;
import com.zx.cloud.service.LogService;
import com.zx.cloud.service.ProposalService;
import com.zx.cloud.service.UserService;
import com.zx.cloud.service.VerifyMsgService;
import com.zx.cloud.util.Page;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


/**
 * 会员
 */
@RestController
@RequestMapping(value = ApiVersion.PROVIDER_V1_PREFIX+"/client")
public class ClientController{

	private static final Logger logger=Logger.getLogger(ClientController.class);
	
	@Autowired
	private ClientService clientService;
	
	@Autowired
	private ProposalService proposalService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private DictService dictService;
	
	@Autowired
	private LogService logService;
	@Autowired     
	private VerifyMsgService  verifyMsgService;
	
	@Autowired 
	private ClientRiskService  clientRiskService;
	
	@RequestLogging
	@IgnoreAuth
	@ApiOperation(value = "手机会员注册" , notes = "手机会员注册")
	@RequestMapping(value = "clientRegister", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Token> clientRegister(HttpServletRequest request, HttpServletResponse response, @RequestBody Client client) throws IllegalArgumentException, JWTCreationException, UnsupportedEncodingException{
		
		long userId = clientService.handleRegisterClient(client);
		Map<String, Object> claims=new HashMap<String, Object>();
    	claims.put(MagicConstants.SESSION_USER_ID,new Long(userId));
    	Token token=TokenGenerator.create(claims);
    	
    	logService.addLog(userId, "手机会员注册", 0);
		return new ObjectDataResponse<Token>(token);
	}
	
	@RequestLogging
	@IgnoreAuth
	@ApiOperation(value = "会员登录操作" , notes = "会员登录操作")
	@RequestMapping(value = "clientLogin", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Token> clientLogin(HttpServletRequest request, HttpServletResponse response, @RequestBody  Client client) throws IllegalArgumentException, JWTCreationException, UnsupportedEncodingException{
		long userId = clientService.handleLoginClient(client);
		
		Map<String, Object> claims=new HashMap<String, Object>();
    	claims.put(MagicConstants.SESSION_USER_ID,new Long(userId));
    	Token token=TokenGenerator.create(claims);
    	
    	logService.addLog(userId, "手机会员登录", 0);
		return new ObjectDataResponse<Token>(token);
	}
	
	@RequestLogging
	@ApiOperation(value = "会员刷新TOKEN操作" , notes = "会员刷新TOKEN操作")
	@RequestMapping(value = "refreshToken", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Token> refreshToken(@CurrentUserId Long userId) throws IllegalArgumentException, JWTCreationException, UnsupportedEncodingException{
		
		Map<String, Object> claims=new HashMap<String, Object>();
    	claims.put(MagicConstants.SESSION_USER_ID,new Long(userId));
    	Token token=TokenGenerator.create(claims);
    	
    	logService.addLog(userId, "刷新会员TOKEN", 0);
		return new ObjectDataResponse<Token>(token);
	}
	
	@RequestLogging
	@IgnoreAuth
	@ApiOperation(value = "会员忘记密码" , notes = "会员忘记密码")
	@RequestMapping(value = "forgotPassword", method = RequestMethod.POST)
	@ResponseBody
	public Response forgotPassword(@RequestBody  Client client){
		int success = clientService.handleForgotPassword(client);
		return new ObjectDataResponse<Integer>(success);
	}
	
	@RequestLogging
	@ApiOperation(value = "会员修改密码" , notes = "会员修改密码")
	@RequestMapping(value = "modifyPassword", method = RequestMethod.POST)
	@ResponseBody
	public Response modifyPassword(@CurrentUserId Long userId,@RequestBody  Client client){
		client.setId(userId);
		int success = clientService.handleModifyPassword(client);
		
		logService.addLog(userId, "手机修改密码", 0);
		return new ObjectDataResponse<Integer>(success);
	}
	
	@RequestLogging
	@ApiOperation(value = "获取会员认证信息" , notes = "获取会员认证信息")
	@RequestMapping(value = "getClientAuth", method = RequestMethod.POST)
	@ResponseBody
	public Response getClientAuth(@CurrentUserId Long userId,@RequestBody  Client client){
		client.setId(userId);
		ClientAuth data = clientService.SelectClientAuth(client);
		
		logService.addLog(userId, "获取会员认证信息", 0);
		return new ObjectDataResponse<ClientAuth>(data);
	}
	
	@RequestLogging
	@ApiOperation(value = "查询会员信息" , notes = "查询会员信息")
	@RequestMapping(value = "queryClient", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Page<Client>> queryClient(
			@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody Client client){
		logger.info("查询会员信息");
		client.setId(userId);
		Page<Client> datas=clientService.page(client);
		
		logService.addLog(userId, "查询会员信息", 0);
		return new ObjectDataResponse<Page<Client>>(datas);
	}
	
	@RequestLogging
	@ApiOperation(value = "修改会员信息" , notes = "修改会员信息")
	@RequestMapping(value = "updateClient", method = RequestMethod.POST)
	@ResponseBody
	public Response updateClient(@CurrentUserId Long userId,@RequestBody  Client client){
		client.setId(userId);
		int success = clientService.update(client);
		
		logService.addLog(userId, "修改会员信息", 0);
		return new ObjectDataResponse<Integer>(success);
	}
	
	/*
	 * @Description:登陆 注册 忘记密码 发送短信验证接口
	 *              smsType 状态码 '0':登陆 '1'：注册 '2'：忘记密码
	 */
	@IgnoreAuth
	@ApiOperation(value = "验证手机-获取验证码", notes = "验证手机-获取验证码")
	@RequestMapping(value = "/sendSMS", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Integer> sendSMS(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody SmsMsg smsMsg){
		
		int success=userService.handleSmsCode(userId, smsMsg.getPhone(), smsMsg.getSmsType()+"");
		
		logService.addLog(userId, "获取验证码", 0);
		return new ObjectDataResponse<Integer>(success);
	}
	
	@IgnoreAuth
	@ApiOperation(value = "判断验证码对错", notes = "判断验证码对错")
	@RequestMapping(value = "/verifyCode", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Integer> verifyCode(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody SmsMsg smsMsg){
		
		int success=userService.verifySmsCode(userId, smsMsg.getPhone(), smsMsg.getCode());
		return new ObjectDataResponse<Integer>(success);
	}
	
	@RequestLogging
	@ApiOperation(value = "查询意见反馈信息" , notes = "查询意见反馈信息")
	@RequestMapping(value = "queryProposal", method = RequestMethod.POST)
	@ResponseBody
	public Response queryProposal(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody Proposal proposal){
		logService.addLog(userId, "查询意见反馈信息", 0);
		Page<Proposal> datas=proposalService.queryProposalpage(proposal);
		return new ObjectDataResponse<Page<Proposal>>(datas);
	}
	
	@RequestLogging
	@ApiOperation(value = "查询意见反馈信息Api" , notes = "查询意见反馈信息APi")
	@RequestMapping(value = "queryProposalApi", method = RequestMethod.POST)
	@ResponseBody
	public Response queryProposalApi(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody Proposal proposal){
		logService.addLog(userId, "查询意见反馈信息Api", 0);
		proposal.setClientId(userId); //会员id
		proposal.setPageSize(10000);
		Page<Proposal> datas=proposalService.queryProposalpage(proposal);
		return new ObjectDataResponse<Page<Proposal>>(datas);
	}
	
	@RequestLogging
	@ApiOperation(value = "修改意见反馈信息" , notes = "修改意见反馈信息")
	@RequestMapping(value = "updateProposal", method = RequestMethod.POST)
	@ResponseBody
	public Response updateProposal(@CurrentUserId Long userId,@RequestBody Proposal proposal){
		logService.addLog(userId, "修改意见反馈信息", 0);
		proposal.setUserId(userId);
		proposal.setBackTime(OffsetDateTime.now());
		proposal.setStatus(1);
		int success=proposalService.update(proposal);
		return new ObjectDataResponse<Integer>(success);
	}
	
	@RequestLogging
	@ApiOperation(value = "添加意见反馈信息API" , notes = "添加意见反馈信息API")
	@RequestMapping(value = "addProposalApi", method = RequestMethod.POST)
	@ResponseBody
	public Response addProposalApi(@CurrentUserId Long userId,@RequestBody Proposal proposal){
		logService.addLog(userId, "添加意见反馈信息", 0);
		proposal.setClientId(userId); //会员id
		proposal.setCreateTime(OffsetDateTime.now());
	    proposal.setStatus(0);
		int success=proposalService.insert(proposal);
		return new ObjectDataResponse<Integer>(success);
	}
	
	@RequestLogging
	@IgnoreAuth
	@ApiOperation(value = "获取中国各大银行" , notes = "获取中国各大银行")
	@RequestMapping(value = "getBanks", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<List<Dict>> getBanks(@CurrentUserId Long userId){
		List<Dict> datas = dictService.getBanks();
		return new ObjectDataResponse<List<Dict>>(datas);
	}
	
	@RequestLogging
	@IgnoreAuth
	@ApiOperation(value = "获取职业" , notes = "获取职业")
	@RequestMapping(value = "getOccpation", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<List<Dict>> getOccpation(@CurrentUserId Long userId){
		List<Dict> datas = dictService.getOccpations();
		return new ObjectDataResponse<List<Dict>>(datas);
	}
	
	@RequestLogging
	@IgnoreAuth
	@ApiOperation(value = "获取学历" , notes = "获取学历")
	@RequestMapping(value = "getEducation", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<List<Dict>> getEducation(@CurrentUserId Long userId){
		List<Dict> datas = dictService.getEducations();
		return new ObjectDataResponse<List<Dict>>(datas);
	}
	
	@IgnoreAuth
	@RequestLogging
	@ApiOperation(value = "身份认证—保存身份证信息" , notes = "身份认证—保存身份证信息")
	@RequestMapping(value = "handleClientIDCardMsg", method = RequestMethod.POST)
	@ResponseBody
	public Response handleClientIDCardMsg(@CurrentUserId Long userId,@RequestBody VerifyMsg verifyMsg){
		int success = clientService.handleClientIDCardMsg(userId, verifyMsg);
		//同盾校验暂时屏蔽
//		verifyMsgService.handlePreLoanMsg(userId, verifyMsg);
		
		//数美校验
		success=verifyMsgService.handlePreLoanMsgByShuMei(userId, verifyMsg);
		
		logService.addLog(userId, "处理认证信息", 0);
		return new ObjectDataResponse<Integer>(success);
	}
	
	@RequestLogging
	@ApiOperation(value = "身份认证—保存身份证图片" , notes = "身份认证—保存身份证图片")
	@RequestMapping(value = "saveIDCardImg", method = RequestMethod.POST)
	@ResponseBody
	public Response saveIDCardImg(@RequestBody IdCardImg idCardImg){
		int success = clientService.saveIDCardImg( idCardImg);
		
		return new ObjectDataResponse<Integer>(success);
	}
	
	@RequestLogging
	@ApiOperation(value = "获取风控数据" , notes = "获取风控数据")
	@RequestMapping(value = "getClientRiskInfo", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Map<String, Object>> getClientRiskInfo(@CurrentUserId Long userId,@RequestBody ClientRisk clientRisk){
		Map<String, Object> resultMap=new HashMap<String, Object>();
		ClientRisk newClientRisk = clientRiskService.getClientRiskSm(clientRisk);
		resultMap.put("shumei_mhl", newClientRisk);//数美多头借贷
		return new ObjectDataResponse<Map<String, Object>>(resultMap);
	}
	
}
